<template>
  <el-dialog
    :title="type === 'add' ? '新增价格方案' : '编辑价格方案'"
    custom-class="custom-class-line"
    :visible.sync="dialogVisible"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    width="1000px"
    @close="closeDialog">
    <div v-loading="loading">
      <el-form :model="form" :rules="rules" ref="form" size="small" label-width="90px" label-position="right">
        <div class="flex">
          <el-form-item style="width:45%" label="方案名称1"  prop="planName">
            <el-input
              v-model="form.planName"
              clearable
              placeholder="请输入"
              style="width:200px"
              :maxlength="50"
            />
          </el-form-item>
          <!--          <el-form-item label="运输类型" prop="transportType">-->
          <!--            <el-select clearable filterable style="width:200px" placeholder="请选择" v-model="form.transportType">-->
          <!--              <el-option-->
          <!--                v-for="(item, index) in dict.type.transport_type"-->
          <!--                :key="index"-->
          <!--                :label="item.label"-->
          <!--                :value="item.value"-->
          <!--              ></el-option>-->
          <!--            </el-select>-->
          <!--          </el-form-item>-->
        </div>
        <div class="flex">
                  <el-form-item style="width:45%" label="计费方式" prop="feeMode">
                      <el-select :disabled="true" filterable style="width:200px" placeholder="请选择" v-model="form.feeMode" @change="handleOnChange">
                        <el-option
                          v-for="(item, index) in dict.type.price_method"
                          :key="index"
                          :label="item.label"
                          :value="item.value"
                        ></el-option>
                      </el-select>
<!--                      <el-checkbox class="ml10" true-label="1" false-label="0" :disabled="form.feeMode === 'mileage'" v-model="form.addFeeMode"  @change="handleCheckboxOnChange">+ 里程</el-checkbox>-->
                    </el-form-item>
          <el-form-item label="状态" prop="status">
            <el-select filterable style="width:200px" placeholder="请选择" v-model="form.status">
              <el-option label="启用" value="0"></el-option>
              <el-option label="禁用" value="1"></el-option>
            </el-select>
          </el-form-item>
        </div>
        <PriceSelect ref="weight" v-if="['weight'].includes(form.feeMode)" feeMode="weight" :data="form.weightList" />
        <PriceSelect ref="volume" v-if="['volume'].includes(form.feeMode)" feeMode="volume" :data="form.volumeList" />
        <PriceSelect ref="pieces" v-if="['pieces'].includes(form.feeMode)" feeMode="pieces" :data="form.piecesList" />
        <div class="flex pl90" v-if="form.feeMode === 'volumeWeight'">
          <el-form-item label-width="0" style="width:45%" label="">*用于计算体积重量，如：体积重量=长×宽×高/轻泡系数*</el-form-item>
          <el-form-item label-width="90px" class="mb5" label="轻泡系数" prop="waterProof"
                        :rules="{
                required: true, message: `轻泡系数不能为空`, trigger: 'blur' }"
          >
            <el-input
              v-model="form.waterProof"
              clearable
              @input="limitInput($event, 'waterProof', form)"
              style="width:120px"
              placeholder="请输入"
            />
          </el-form-item>
        </div>
        <div class="flex pl90 mb-2" style="margin-bottom: 10px;" v-if="form.feeMode === 'weightMultiMileage'">
          <el-form-item label-width="80px" class="mb5" label="最低计重" prop="waterProof"
                        :rules="{
                required: true, message: `最低计重不能为空`, trigger: 'blur' }"
          >
            <el-input
              v-model="form.waterProof"
              clearable
              @input="limitInput($event, 'waterProof')"
              style="width:120px"
              placeholder="请输入"
            /><span style="margin-left: 5px">吨</span>
          </el-form-item>
        </div>
        <PriceSelect ref="volumeWeight" v-if="['volumeWeight'].includes(form.feeMode)" feeMode="volumeWeight" :data="form.volumeWeightList" />
        <PriceSelect ref="mileage" v-if="['mileage', 'weightMultiMileage'].includes(form.feeMode) || form.addFeeMode === '1' || form.addFeeMode === '6'" feeMode="mileage" :data="form.mileageList"/>
        <!--        <div>
                  <el-form-item label="">默认通用价格，应用于所有区域、线路</el-form-item>
                </div>-->
        <!--        <div>-->
        <!--          <el-checkbox class="mb10" v-model="form.isAssociatedArea" @change="val => handleRelationOnChange(val,'districtId')">关联区域</el-checkbox>-->
        <!--          <el-form-item label="应用区域" v-if="form.isAssociatedArea">-->
        <!--            <virtual-select-->
        <!--              style="width:220px"-->
        <!--              v-model="form.districtId"-->
        <!--              :list="areaList"-->
        <!--              label="addressName"-->
        <!--              value="cityId"-->
        <!--              placeholder="请输入关键字匹配"-->
        <!--              :keeps-params="10"-->
        <!--              @change="val => handleChange(val, 'districtId')"-->
        <!--              :is-multiple="true"-->
        <!--              :disabled="false"-->
        <!--              :allow-create="false"-->
        <!--            />-->
        <!--          </el-form-item>-->
        <!--        </div>-->
        <!--        <template v-if="form.distLineList && form.distLineList.length">-->
        <!--          <el-form-item label="" class="position-relative">-->
        <!--            <div style="background-color: #D7D7D7;" class="pl10" v-for="item in form.distLineList" :key="item.distId">-->
        <!--              {{item.distName}} 【包含{{item.lineNum}}条线路】-->
        <!--            </div>-->
        <!--            <el-tag style="position:absolute;right:0;top:0" type="info">共{{total1}}个省市区域，已选择{{form.distLineList && form.distLineList.length || 0}}个省市区域</el-tag>-->
        <!--          </el-form-item>-->
        <!--        </template>-->
        <!--        <div>-->
        <!--          <el-checkbox class="mb10" v-model="form.isAssociatedLine" @change="val => handleRelationOnChange(val,'lineId')">关联线路</el-checkbox>-->
        <!--          <el-form-item label="应用线路" v-if="form.isAssociatedLine">-->
        <!--            <virtual-select-->
        <!--              style="width:220px"-->
        <!--              v-model="form.lineId"-->
        <!--              @change="val => handleChange(val, 'lineId')"-->
        <!--              :list="lineList"-->
        <!--              label="lineName"-->
        <!--              value="lineId"-->
        <!--              placeholder="请输入关键字匹配"-->
        <!--              :keeps-params="10"-->
        <!--              :is-multiple="true"-->
        <!--              :disabled="false"-->
        <!--              :allow-create="false"-->
        <!--            />-->
        <!--          </el-form-item>-->
        <!--        </div>-->
        <!--        <template v-if="form.lineList && form.lineList.length">-->
        <!--          <el-form-item label="" class="position-relative">-->
        <!--            <div style="background-color: #D7D7D7;" class="pl10" v-for="item in form.lineList" :key="item.lineId">-->
        <!--              {{item.lineName}} {{selectDictLabel(dict.type.line_scope, item.lineScope)}} {{selectDictLabel(dict.type.line_type, item.lineType)}}【{{selectDictLabel(dict.type.line_flag, item.lineFlag)}}】 {{ (item.stationList || []).map(v => v.branchDept && v.branchDept.deptCode).join('>') }}-->
        <!--            </div>-->
        <!--            <el-tag style="position:absolute;right:0;top:0" type="info">共{{total2}}条线路，已选择{{form.lineList && form.lineList.length || 0}}条线路</el-tag>-->
        <!--          </el-form-item>-->
        <!--        </template>-->
      </el-form>
      <div class="text-center">
        <el-button v-if="type === 'add'" :loading="btnLoading" type="primary" @click="submitForm">确定新增</el-button>
        <el-button v-else :loading="btnLoading" type="primary" @click="submitForm">确定修改</el-button>
        <el-button type="canceL" @click="closeDialog">取消</el-button>
      </div>
    </div>
  </el-dialog>
</template>

<script>
import PriceSelect from '../components/priceSelect.vue'
import {
  randomString,
  elFormErrorScrollIntoView
} from "@/utils/zito"
import { getAllCityInfo  } from "@/api/login";
import {
  pricePlanAdd,
  pricePlanDetail,
  pricePlanEdit
} from "@/api/system/price";
import {
  onlineList,
  lineDetail
} from "@/api/system/line";
var cloneDeep = require('lodash.clonedeep');
export default {
  components: {
    PriceSelect
  },
  dicts: ['transport_type','price_method','line_scope','line_direct','line_type', 'line_flag', 'dept_type'],
  props: {
    /* type: {
      type: String,
      default: 'add'
    }, */
    isOpen: {
      type: String | Number,
      default: ''
    }
  },
  data() {
    return {
      dialogVisible: false,
      form: {
        feeMode: 'weightMultiMileage'
      },
      rules: {
        planName: [
          { required: true, message: '方案名称不能为空', trigger: 'blur' },
        ],
        status: [
          { required: true, message: '使用状态不能为空', trigger: 'change' },
        ],
        feeMode: [
          { required: true, message: '计费方式不能为空', trigger: 'change' },
        ],
        // transportType: [
        //   { required: true, message: '运输类型不能为空', trigger: 'change' },
        // ],
        districtId: [
          { required: true, message: '关联区域不能为空', trigger: 'change' },
        ],
        lineId: [
          { required: true, message: '关联线路不能为空', trigger: 'change' },
        ],
      },
      methodsList: [
        'mileage',
        'weight',
        'volume',
        'pieces',
        'volumeWeight',
      ],
      areaList: [],
      lineList: [],
      btnLoading:  false,
      loading: false,
      oldDistLineList: [],
      oldLineList: [],
      total1:0,
      total2:0,

      type: '',
    };
  },
  methods: {
    showDialog(row, type) {
      this.type = type
      this.dialogVisible = true
      getAllCityInfo().then(res => {
        this.areaList = res.data
        this.total1 = res.data.length
      });
      onlineList().then(res => {
        this.lineList = res.rows
        this.total2 = res.total
      });
      if (this.type === 'add') {
        this.$set(this.form, 'addFeeMode','0')
        this.$set(this.form, 'status','0')
        this.$set(this.form, 'feeMode','weightMultiMileage')
        this.$set(this.form, 'isAssociatedArea',false)
        this.$set(this.form, 'isAssociatedLine',false)
        this.$set(this.form, 'districtId',[])
        this.$set(this.form, 'lineId',[])
        this.$set(this.form, 'mileageList',[
          {
            feeMode: 'mileage',
            floatStart:0,
            intStart:0,
            uuid: randomString(32)
          },
          {
            feeMode: 'mileage',
            uuid: randomString(32)
          }
        ])
      } else {
        this.loading = true;
        pricePlanDetail(row.id).then(res => {
          this.form = res.data;
          this.form.addFeeMode = this.form.addFeeMode === 'mileage' ? '1' : '0'
          this.form.districtId = this.form.districtId && this.form.districtId.split(',') || []
          this.form.lineId = this.form.lineId && this.form.lineId.split(',') || []
          this.$set(this.form, 'districtId', this.form.districtId)
          this.$set(this.form, 'lineId', this.form.lineId)
          this.oldDistLineList = cloneDeep(this.form.distLineList) || []
          this.oldLineList = cloneDeep(this.form.lineList) || []
          if (this.form.districtId && this.form.districtId.length) {
            this.$set(this.form, 'isAssociatedArea',true)
          }
          if (this.form.lineId && this.form.lineId.length) {
            this.$set(this.form, 'isAssociatedLine',true)
          }
          this.form.mileageList = this.form.segList && this.form.segList.filter(v => v.feeMode === 'mileage') || []
          this.form.weightList = this.form.segList && this.form.segList.filter(v => v.feeMode === 'weight') || []
          this.form.volumeList = this.form.segList && this.form.segList.filter(v => v.feeMode === 'volume') || []
          this.form.piecesList = this.form.segList && this.form.segList.filter(v => v.feeMode === 'pieces') || []
          this.form.volumeWeightList = this.form.segList && this.form.segList.filter(v => v.feeMode === 'volumeWeight') || []
          this.$set(this.form, 'mileageList', this.form.mileageList)
          this.$set(this.form, 'weightList', this.form.weightList)
          this.$set(this.form, 'volumeList', this.form.volumeList)
          this.$set(this.form, 'piecesList', this.form.piecesList)
          this.$set(this.form, 'volumeWeightList', this.form.volumeWeightList)
        }).finally(()=>{
          this.loading = false;
        });
      }
    },
    closeDialog(e) {
      this.dialogVisible = false
      this.form={feeMode: 'weightMultiMileage'}
      e === true && this.$emit('close')
    },
    async handleValidate() {
      try {
        await this.$refs.form.validate()
        return Promise.resolve(true)
      } catch (error) {
        return Promise.resolve(false)
      }
    },
    async submitForm() {
      const formValidate = await this.handleValidate()
      let promiseArray = [];
      for(let i = 0;i<this.methodsList.length;i++){
        promiseArray.push(new Promise(async(resolve) => {
          const result = this.$refs[this.methodsList[i]] ? await this.$refs[this.methodsList[i]].handleValidate() : true
          if (result) resolve(true)
          else resolve(false)
        }))
      }
      const resultArray = await Promise.all(promiseArray)
      const resultAll = resultArray.every(v => v)
      if(formValidate && resultAll){
        let form = cloneDeep(this.form)
        form.districtId = form.districtId && form.districtId.join(',')
        form.lineId = form.lineId && form.lineId.join(',')
        form.segList = [
          ...form.mileageList || [],
          ...form.weightList || [],
          ...form.volumeList || [],
          ...form.piecesList || [],
          ...form.volumeWeightList || [],
        ]
        form.segList = form.segList.map((v,k) => {
          return {
            ...v,
            sort: k,
            planId: form.id
          }
        })

        form.addFeeMode = +form.addFeeMode === 1 ? 'mileage' : ''
        // 前端需要，后端不需要的字段
        const words = ['mileageList','weightList','volumeList','piecesList','volumeWeightList','isAssociatedArea','isAssociatedLine','lineList','distLineList']
        for (let index = 0; index < words.length; index++) {
          if (form.hasOwnProperty(words[index])) {
            delete form[words[index]]
          }
        }

        if (this.form.status === '0' && this.isOpen !== '' && this.isOpen !== form.id) return this.$message.error('只能启用一种方案')

        this.btnLoading = true
        const params = form.id ? pricePlanEdit : pricePlanAdd
        form.segList=form.segList.filter(item=>item.feeMode!=='weight') //前端过滤weight字段
        params(form).then(res => {
          this.$message.success(form.id ? '编辑成功' : '新增成功')
          this.closeDialog(true)
        }).finally(()=> {
          this.btnLoading = false
        });
      } else {
        this.$nextTick(() => {
          elFormErrorScrollIntoView();
        });
      }
    },
    handleOnChange() {
      this.$set(this.form, 'mileageList', [])
      this.$set(this.form, 'weightList', [])
      this.$set(this.form, 'volumeList', [])
      this.$set(this.form, 'piecesList', [])
      this.$set(this.form, 'volumeWeightList', [])
      this.$set(this.form, 'weightMultiMileage', [])
      if (this.form.feeMode === "mileage") {
        this.$set(this.form, 'addFeeMode', '0')
      }
      this.$set(this.form, `${this.form.feeMode}List`, [
        {
          feeMode: this.form.feeMode,
          uuid: randomString(32)
        },
        {
          feeMode: this.form.feeMode,
          uuid: randomString(32)
        }
      ])
      if (this.form.addFeeMode === '1') {
        this.$set(this.form, 'mileageList', [
          {
            feeMode: 'mileage',
            uuid: randomString(32)
          },
          {
            feeMode: 'mileage',
            uuid: randomString(32)
          }
        ])
      }
    },
    handleCheckboxOnChange(val) {
      if (val === '0') {
        this.$set(this.form, 'mileageList', [])
      } else {
        this.$set(this.form, 'mileageList', [
          {
            feeMode: 'mileage',
            uuid: randomString(32)
          },
          {
            feeMode: 'mileage',
            uuid: randomString(32)
          }
        ])
      }
    },
    handleRelationOnChange(val,key) {
      if (key === 'districtId') {
        this.$set(this.form, 'districtId', [])
        this.$set(this.form, 'distLineList', [])
      } else if (key === 'lineId') {
        this.$set(this.form, 'lineId', [])
        this.$set(this.form, 'lineList', [])
      }
    },
    handleChange(val,key) {
      if (key === 'districtId') {
        this.$set(this.form, 'distLineList', [])
        for (let index = 0; index < val.length; index++) {
          const item = this.oldDistLineList.find(v => v.distId === val[index])
          if (item) {
            this.form.distLineList.splice(index, 0, item)
          } else {
            lineList({lineDistrict: val[index]}).then(res => {
              const total = res.total
              const obj = this.areaList.find(v => v.cityId === val[index]) || {}
              this.oldDistLineList.push({distId:obj.cityId,distName: obj.addressName,lineNum: total})
              this.form.distLineList.splice(index, 0, {distId:obj.cityId,distName: obj.addressName,lineNum: total})
            });
          }
        }
      } else if (key === 'lineId') {
        this.$set(this.form, 'lineList', [])
        for (let index = 0; index < val.length; index++) {
          const item = this.oldLineList.find(v => v.lineId === val[index])
          if (item) {
            this.form.lineList.splice(index, 0, item)
          } else {
            lineDetail(val[index]).then(res => {
              const obj = this.lineList.find(v => v.lineId === val[index]) || {}
              this.oldLineList.push(obj)
              this.form.lineList.splice(index, 0, obj)
            });
          }
        }
      }
    },
    limitInput(value, name) {
      this.form[name] = ('' + value) // 第一步：转成字符串
        .replace(/[^\d^\.]+/g, '') // 第二步：把不是数字，不是小数点的过滤掉
        .replace(/^0+(\d)/, '$1') // 第三步：第一位0开头，0后面为数字，则过滤掉，取后面的数字
        .replace(/^\./, '0.') // 第四步：如果输入的第一位为小数点，则替换成 0. 实现自动补全
        .match(/^\d*(\.?\d{0,3})/g)[0] || '' // 第五步：最终匹配得到结果 以数字开头，只有一个小数点，而且小数点后面只能有0到2位小数
    },
  }
};
</script>
<style lang="scss">
</style>
